# -*- coding:utf-8 -*-


"""
@version: v1.0
@author: 夏伟坤
@Email: 915624876@qq.com
@software: PyCharm
@project: ParsingExcelTables
@file: excel_parsing.py
@time: 2021/10/22 21:37
"""

import os

from core.utils.log_helper import logger  # 导入logger对象

logger.info("启动自动上传文件应用")


"""
解析excel功能：

"""

class ParsingExcelTables:
    # 解析excel表
    def __init__(self):
        pass

    @staticmethod
    def getFileInfo(userDir, fileType):  # 获取文件夹下的所有excel表绝对路径
        """
        获取文件夹下的所有excel表绝对路径，返回列表

        :param userDir: 用户选择的文件夹
        :return: 返回搜索到的所有excel表的列表绝对路径
        """
        try:
            # 判断fileType是excel还是all
            if fileType == "excel":
                # 执行搜索excel
                excelList = []
                for filepath, dirnames, filenames in os.walk(userDir):
                    for filename in filenames:
                        path = os.path.join(filepath, filename)  # 文件路径

                        file = os.path.splitext(path)  # 分割文件名和拓展名
                        _, filetype = file  # 获取文件名和拓展名

                        if filetype in [".xlsx", ".xls"]:
                            excelList.append(path)

                if not excelList:
                    # 选择的文件夹没有excel文件
                    logger.warning("选择的文件夹没有excel文件")
                    # QMessageBox.information(self, "警告", f"找不到文件夹：{inputpath}，请检查目录以及单号是否填写有误，")
                    # QMessageBox.warning(self, "警告", "选择的文件夹没有excel文件")
                    return "选择的文件夹没有excel文件"
                print(excelList)
                return excelList
            elif fileType == "all":
                # 获取所有的文件
                pass
            else:
                logger.error("类型选择错误")



        except Exception as e:
            logger.error(e)

    @staticmethod
    def parsingExcelTables(excelPath):  # excelPath:excel表路径
        """
        解析excel表格，返回字典json

        :param excelPath:
        :return:
        """
        import xlrd
        import json
        data = xlrd.open_workbook(excelPath)
        allsheetnames = data.sheet_names()  # 获取页签名字
        sheet2 = []
        for i in range(len(data.sheets())):
            # 获取一个工作表
            table = data.sheets()[i]

            rows = table.nrows  # 行
            cols = table.ncols  # 列

            # dict1 = {"字段1": "a1", "字段2": "a2", "字段3": "a3", ...}
            dict1 = {}

            # sheet1 = [
            #     {"字段1": "a1", "字段2": "a2", "字段3": "a3", ...},
            #     {"字段1": "b1", "字段2": "b2", "字段3": "b3", ...},
            #     ...
            # ]
            sheet1 = []

            for j in range(cols):
                # 获取第一行的字段，并生成无value值的空字典
                row = 0
                dict1[table.cell(row, j).value] = ''
            for k in range(1, rows):
                # 从第二行开始获取每一行的值，并把值与第一行的字段zip成字典，append到sheet1列表中
                a = table.row_values(k)
                # print(a)
                dict1 = dict(zip(dict1.keys(), a))
                sheet1.append(dict1)

            dict2 = {allsheetnames[i]: sheet1}

            # 转json格式
            # print(type(json.dumps(dict2, ensure_ascii=False)))
            sheet2.append(json.dumps(dict2, ensure_ascii=False))
            sheet2.append(dict2)

        print(sheet2)
        dict3 = {
            "dir": excelPath,
            "msg": sheet2
        }
        return json.dumps(dict3, ensure_ascii=False)

    def reqAssemblyUpload(self, jsonData):  # jsonData:解析后的数据
        """
        Assembly upload 汇编上传接口

        :param jsonData:
        :return:
        """
        pass

    def main(self, userDir):
        """执行"""
        excelPathList = self.recognizeDir(userDir)
        for excelPath in excelPathList:
            # 调用解析表格方法
            jsonData = self.parsingExcelTables(excelPath)
            rsp = self.reqAssemblyUpload(jsonData)
            if rsp.code == 1:
                print("成功")


if __name__ == '__main__':
    pass
